<template>
  <div class="order-detail-container">
    <el-page-header @back="goBack" :content="pageTitle" />
    
    <div v-if="loading" class="loading-spinner">
      <el-progress :percentage="50" :indeterminate="true" />
      <p>正在加载订单详情...</p>
    </div>

    <template v-else-if="error">
      <el-result icon="error" title="订单加载失败" :sub-title="error">
        <template #extra>
          <el-button type="primary" @click="goToOrderHistory">返回订单列表</el-button>
          <el-button @click="fetchOrderDetails">重试</el-button>
        </template>
      </el-result>
    </template>

    <template v-else-if="order">
      <el-card style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <h3>订单号: {{ order.order_number }}</h3>
            <el-tag :type="getStatusTagType(order.status)" size="large">
              {{ order.status_display || order.status }}
            </el-tag>
          </div>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单总金额">
            <strong style="color: #ff4d4f;">¥{{ order.total_amount }}</strong>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ order.payment_method_display || order.payment_method }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ formatDateTime(order.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后更新">
            {{ formatDateTime(order.updated_at) }}
          </el-descriptions-item>
          
          <el-descriptions-item v-if="order.shipped_at" label="发货时间">
            {{ formatDateTime(order.shipped_at) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="order.completed_at" label="完成时间">
            {{ formatDateTime(order.completed_at) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="order.cancelled_at" label="取消时间">
            {{ formatDateTime(order.cancelled_at) }}
          </el-descriptions-item>
          
          <el-descriptions-item label="收货人">
            {{ order.shipping_recipient_name }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ order.shipping_phone_number }}
          </el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">
            {{ formatAddress(order) }}
          </el-descriptions-item>
          <el-descriptions-item v-if="order.customer_remarks" label="用户备注" :span="2">
            {{ order.customer_remarks }}
          </el-descriptions-item>
        </el-descriptions>

        <h4 style="margin-top: 30px; margin-bottom: 15px;">商品信息</h4>
        <el-table :data="order.items" border style="width: 100%">
          <el-table-column prop="product_name_at_purchase" label="商品名称" />
          <el-table-column prop="price_at_purchase" label="单价" width="120">
            <template #default="scope">¥{{ scope.row.price_at_purchase }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column prop="subtotal" label="小计" width="120">
            <template #default="scope">¥{{ scope.row.subtotal }}</template>
          </el-table-column>
        </el-table>

        <div v-if="order.status_history?.length" style="margin-top: 30px;">
          <h4>订单追踪</h4>
          <el-timeline>
            <el-timeline-item 
              v-for="(history, index) in order.status_history" 
              :key="index" 
              :timestamp="formatDateTime(history.changed_at)"
              :type="index === 0 ? 'primary' : ''"
            >
              <p>状态: {{ history.status_display || history.status }}</p>
              <p v-if="history.notes">备注: {{ history.notes }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div style="margin-top: 30px; text-align: right;">
          <el-button 
            v-if="canCancelOrder" 
            type="danger" 
            @click="handleCancelOrder"
            :loading="cancelling"
          >
            取消订单
          </el-button>
          <el-button @click="goToOrderHistory">返回订单列表</el-button>
        </div>
      </el-card>
    </template>

    <div v-else class="empty-order">
      <el-empty description="未找到指定的订单信息。" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import orderService from '../api/order.service';

const route = useRoute();
const router = useRouter();

const order = ref(null);
const loading = ref(true);
const error = ref(null);
const cancelling = ref(false);

const pageTitle = computed(() => order.value ? `订单详情: ${order.value.order_number}` : '订单详情');

const canCancelOrder = computed(() => {
  return order.value?.status === 'processing';
});

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return 'N/A';
  try {
    return new Date(dateTimeString).toLocaleString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (e) {
    return dateTimeString;
  }
};

const formatAddress = (order) => {
  if (!order) return 'N/A';
  const parts = [
    order.shipping_province,
    order.shipping_city,
    order.shipping_district,
    order.shipping_street_address
  ].filter(Boolean);
  
  let result = parts.join('');
  if (order.shipping_postal_code) {
    result += ` (邮编: ${order.shipping_postal_code})`;
  }
  return result;
};

const getStatusTagType = (status) => {
  const statusMap = {
    processing: 'warning',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger',
    pending_payment: 'info'
  };
  return statusMap[status] || 'info';
};

const fetchOrderDetails = async () => {
  if (!route.params.orderNumber) {
    error.value = '订单号不能为空';
    loading.value = false;
    return;
  }

  try {
    loading.value = true;
    error.value = null;
    
    const response = await orderService.getOrder(route.params.orderNumber);
    if (!response?.data) {
      throw new Error('获取订单详情失败');
    }
    
    order.value = response.data;
  } catch (err) {
    console.error('获取订单详情失败:', err);
    error.value = err.message || '获取订单详情失败';
    ElMessage.error(error.value);
  } finally {
    loading.value = false;
  }
};

const handleCancelOrder = async () => {
  if (!order.value?.id) return;

  try {
    await ElMessageBox.confirm(
      '您确定要取消此订单吗？此操作可能无法撤销。',
      '确认取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning',
      }
    );

    cancelling.value = true;
    await orderService.cancelOrder(order.value.id);
    ElMessage.success('订单已成功取消');
    await fetchOrderDetails();
  } catch (err) {
    if (err !== 'cancel') {
      console.error('取消订单失败:', err);
      ElMessage.error(err.message || '取消订单操作失败');
    }
  } finally {
    cancelling.value = false;
  }
};

const goBack = () => {
  router.push({ name: 'OrderHistory' });
};

const goToOrderHistory = () => {
  router.push({ name: 'OrderHistory' });
};

// 监听路由参数变化
watch(() => route.params.orderNumber, (newOrderNumber) => {
  if (newOrderNumber) {
    fetchOrderDetails();
  }
}, { immediate: true });

onMounted(() => {
  if (route.params.orderNumber) {
    fetchOrderDetails();
  }
});

onBeforeUnmount(() => {
  // 清理状态
  order.value = null;
  loading.value = true;
  error.value = null;
  cancelling.value = false;
});
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.el-page-header {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-spinner,
.error-message,
.empty-order {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  margin-top: 20px;
}

.el-descriptions {
  margin-top: 10px;
}

h4 {
  font-size: 1.1em;
  color: #303133;
}
</style> 